package service

import (
	"sen-golang-study/go_game_study/hero_story_go_server/game_server/internal/domain/user/entity"
	"sen-golang-study/go_game_study/hero_story_go_server/game_server/internal/domain/user/repository"
	"sen-golang-study/go_game_study/hero_story_go_server/game_server/internal/domain/user/valueobject"
	"time"
)

// UserDomainService 用户领域服务
type UserDomainService struct {
	userRepo repository.UserRepository
}

// NewUserDomainService 创建用户领域服务
func NewUserDomainService(userRepo repository.UserRepository) *UserDomainService {
	return &UserDomainService{
		userRepo: userRepo,
	}
}

// LoginByPassword 根据用户名和密码登录
func (s *UserDomainService) LoginByPassword(userName, password string) (*entity.User, error) {
	if len(userName) <= 0 || len(password) <= 0 {
		return nil, nil
	}

	// 通过仓储获取用户数据
	user, err := s.userRepo.GetByUserName(userName)
	if err != nil {
		return nil, err
	}

	nowTime := time.Now().UnixMilli()

	if user == nil {
		// 如果用户不存在，创建新用户
		user = entity.NewUser(userName, password, "Hero_Hammer", nowTime)
		user.SetCurHP(1000)
	}

	// 更新最后登录时间
	user.UpdateLastLoginTime(nowTime)

	// 保存或更新用户
	err = s.userRepo.SaveOrUpdate(user)
	if err != nil {
		return nil, err
	}

	return user, nil
}

// GetUserByID 根据用户ID获取用户
func (s *UserDomainService) GetUserByID(userID uint32) (*entity.User, error) {
	return s.userRepo.GetByUserID(userID)
}

// GetUserByName 根据用户名获取用户
func (s *UserDomainService) GetUserByName(userName string) (*entity.User, error) {
	return s.userRepo.GetByUserName(userName)
}

// UpdateUserPosition 更新用户位置
func (s *UserDomainService) UpdateUserPosition(user *entity.User, fromX, fromY, toX, toY float32) error {
	if user == nil {
		return nil
	}

	// 创建新的移动状态
	moveState := valueobject.NewMoveStateWithPositions(fromX, fromY, toX, toY, time.Now().UnixMilli())
	user.SetMoveState(moveState)

	// 更新用户信息
	return s.userRepo.Update(user)
}

// UserAttack 用户攻击
func (s *UserDomainService) UserAttack(attacker *entity.User, target *entity.User, damage uint32) error {
	if attacker == nil || target == nil {
		return nil
	}

	// 检查攻击者是否存活
	if !attacker.IsAlive() {
		return nil
	}

	// 检查目标是否存活
	if !target.IsAlive() {
		return nil
	}

	// 对目标造成伤害
	target.TakeDamage(damage)

	// 更新目标用户信息
	return s.userRepo.Update(target)
}

// HealUser 治疗用户
func (s *UserDomainService) HealUser(user *entity.User, healAmount uint32) error {
	if user == nil {
		return nil
	}

	// 治疗用户
	user.Heal(healAmount)

	// 更新用户信息
	return s.userRepo.Update(user)
}

// SaveUser 保存用户
func (s *UserDomainService) SaveUser(user *entity.User) error {
	if user == nil {
		return nil
	}
	return s.userRepo.SaveOrUpdate(user)
}